<?php

class seoLinks extends CWidget
{
	public $position = 'top';
	public $linkCount = 1;
	public static $publishedLinks = [ ];

	public function run()
	{
		$datas = [];
		for( $i = 0; $i < $this->linkCount; $i++ )
		{
			$condition = "";
			if( self::$publishedLinks )
			{
				foreach( self::$publishedLinks as $link )
				{
					$condition .= " AND \"linkContent\" NOT LIKE '%href=\"" . $link . "\"%' ";
				}
			}
			$sql = "SELECT * FROM {{seolinks}} WHERE \"linkType\" = '{$this->position}' AND \"linkActive\"=1 " . $condition . " ORDER BY \"linkLastShowed\" ASC LIMIT 1; ";
			$links = Yii::app()->db->createCommand( $sql )->queryAll( TRUE );

			if( $links )
			{
				$link = $links[ 0 ];

				preg_match( '@<a[^>]*href.*?=.*?"([^"]*)"[^>]*>@', $link[ 'linkContent' ], $url );
				self::$publishedLinks[] = $url[ 1 ];

				Yii::app()->db->createCommand( "UPDATE {{seolinks}} SET \"linkPublishCount\"=\"linkPublishCount\"+1, \"linkLastShowed\" = " . time() . " WHERE \"linkId\" = " . $link[ 'linkId' ] . ";" )->execute();
				$datas[] = $link;
			}
		}

		$this->render( 'seolinks', ['links' => $datas, 'position' => $this->position ] );

		return false;
	}

}
